// page p0003 controller
var p0003Controller = (function($) {

	var key = 'p0003';
	var selector = '#' + key;
	var page = 'pages/' + key + '.html';
	var isCreateNew;
	var tryCount = 0;

	var validatePassword = function (password) {
		if (!password)
			return false;

		if (typeof password != 'string')
			return false;

		if (password.length < 6)
			return false;

		return true;
	};

	var draw = function (createNew) {
		$('#p0003CreatePassword').hide();
		$('#p0003ModifyPassword').hide();
		$('#p0003NewPassword').val('');
		$('#p0003OldPassword').val('');
		$('#p0003IntentNewPassword').val('');

		var selector = createNew ? '#p0003CreatePassword' : '#p0003ModifyPassword';
		$(selector).show();
	};

	var showDialog = function (createNew, callback, queryParams) {
		$.esPage.showDialog(selector, {
			callback: callback,
			queryParams: queryParams
		});
		app.afterLoad(selector);
		draw(createNew);
		isCreateNew = createNew;
	};

	var obj = {

		init: function (callback) {
			app.loadPage(page, function () {
				$(selector).esPage();
				if (callback)
					callback();
			});
		},

		refresh: draw,
		showDialog: showDialog,

		btnCancelClick: function () {
			if (isCreateNew && !confirm('没密码保护这个保险箱会很危险哦, 你确定?'))
				return;

			$.esPage.closeDialog(true);
		},

		btnCreatePasswordClick: function () {
			var password = $('#p0003NewPassword').val();
			if (!validatePassword(password)) {
				alert('记得新密码要写复杂点, 多写点字母, 至少六个好吧.');
				return;
			}
			PlatformSupport.modifyPassword(password, function () {
				$.esPage.closeDialog(false);
			});
		},

		btnModifyPasswordClick: function () {
			var oldPassword = $('#p0003OldPassword').val();
			var intentPassword = $('#p0003IntentPassword').val();
			if (!validatePassword(intentPassword)) {
				alert('记得新密码要写复杂点, 多写点字母, 至少六个好吧.');
				return;
			}

			PlatformSupport.checkPassword(oldPassword, function (currect) {
				if (!currect) {
					if (tryCount >= 2)
						$('#p0003ModifyButton').hide();
					else
						alert('要把原来密码输对才能改密码, 还剩 ' + (2-tryCount) + ' 次机会哦');
					tryCount++;
					return;
				}

				PlatformSupport.modifyPassword(intentPassword, function () {
					$.esPage.closeDialog(false);
				});
			});
		}
	};

	app.registerPageController(key, obj);

	return obj;

})(jQuery);